package com.centriole.service.workflow.util;

import java.lang.reflect.Field;
import java.util.*;

/**
 * Created by 梁亮 on 2015/12/21 0021.
 * Cell:15884457479
 * Email:dreamto1@126.com
 * Description:
 * <p/>
 * Functions:
 * 1.
 */
public class Obj2Entity {

    public static <T> T map2Entity(Map<String,Object> map,Class<T> entityClass)
            throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException {
        if(map==null||map.size()==0)
            return null;
        if(entityClass==null)
            return null;

        T result = (T)Class.forName(entityClass.getName()).newInstance();
        Field[] fields = entityClass.getDeclaredFields();
        Set<String> set = map.keySet();
        for (Field field : fields) {
            if(set.contains(field.getName())) {
                field.setAccessible(true);
                if (field.getType().equals(Integer.class) || field.getType().equals(int.class)) {
                    field.set(result, Integer.valueOf(map.get(field.getName()).toString()));
                } else if (field.getType().equals(Date.class)) {
                    field.set(result, CommonUtil.getDateBySecond(map.get(field.getName()).toString()));
                } else {
                    field.set(result, map.get(field.getName()));
                }
            }
        }
        return result;
    }

    public static <T> List<T> map2Entity(List<Map<String,Object>> mapList,Class<T> entityClass)
            throws ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        List<T> result = new ArrayList<T>();
        for (Map<String, Object> map : mapList) {
            result.add(map2Entity(map,entityClass));
        }
        return result;
    }
}
